package com.xu.easyexcel.commons.utils;

import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class CSVUtils {

    /**
     * CSV文件生成方法
     *判断文件是否存在，如果存在则加加入，如果不存在则新建一个文件加入
     */
    public static File createCSVFile(List<Object> head, List<List<Object>> dataList, String outPutPath, String filename) {

        File csvFile = null;
        BufferedWriter csvWtriter = null;
        try {
            csvFile = new File(outPutPath + File.separator + filename + ".csv");
            File parent = csvFile.getParentFile();
            //创建文件夹
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }
            //创建文件
            if(!csvFile.exists()) {
                csvFile.createNewFile();
            }else{
                List<String> addList = new ArrayList<>();
                addList.add(LocalDateTime.now().toString());
                addList.add(LocalDateTime.now().toString());
                addList.add(LocalDateTime.now().toString());

                CSVUtils.append(csvFile.getAbsolutePath(),addList);
            }

            // GB2312使正确读取分隔符","
            csvWtriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
                    csvFile), "GB2312"), 1024);
            // 写入文件头部
            writeRow(head, csvWtriter);

            // 写入文件内容
            for (List<Object> row : dataList) {
                writeRow(row, csvWtriter);
            }
            csvWtriter.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                csvWtriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return csvFile;
    }

    /**
     * 写一行数据方法
     * @param row
     * @param bufferedWriter
     * @throws IOException
     */
    private static void writeRow(List<Object> row, BufferedWriter bufferedWriter) throws IOException {
        // 写入文件头部
        for (Object data : row) {
            StringBuffer sb = new StringBuffer();
            String rowStr = sb.append("\"").append(data).append("\",").toString();
            bufferedWriter.write(rowStr);
        }
        bufferedWriter.newLine();
    }

    public static void append(String file, List<String> dataList) {
        BufferedWriter out = null;
        try {
            String rowStr = "";
            StringBuffer sb = new StringBuffer();
            for (Object data : dataList) {
                rowStr = sb.append("\"").append(data).append("\",").toString();
            }
            out = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(file, true)));
            out.write(rowStr+"\r\n");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @SuppressWarnings("static-access")
    public static void main(String[] args) {
        List<Object> exportData = new ArrayList<Object>();
        exportData.add("第一列");
        exportData.add("第二列");
        exportData.add("第三列");
        List<List<Object>> datalist = new ArrayList<List<Object>>();

        List<Object> data=new ArrayList<Object>();
        data.add("111");
        data.add("222");
        data.add("333");

        List<Object> data1=new ArrayList<Object>();
        data1.add("444");
        data1.add("555");
        data1.add("666");
        datalist.add(data);
        datalist.add(data1);
        String path = "d:/exportCsv/";

        LocalDateTime localDateTime = LocalDateTime.now();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String fileName = dateTimeFormatter.format(localDateTime);

        File file = CSVUtils.createCSVFile(exportData, datalist, path, fileName);
        String fileName2 = file.getName();
        System.out.println("文件名称：" + fileName2);
    }

}
